import { defineStore } from 'pinia'
import { ref, computed, readonly } from 'vue'
import { useChatService, type ChatSession } from '@/services/chat'
import type { ChatMessage, ChatCompletionRequest } from '@/types'

export const useChatStore = defineStore('chat', () => {
  const chatService = useChatService()

  // 状态
  const sessions = ref<Map<string, ChatSession>>(new Map())
  const messages = ref<Map<string, ChatMessage[]>>(new Map()) // sessionId -> messages
  const currentSessionId = ref<string | null>(null)
  const isStreaming = ref<boolean>(false)
  const currentStreamingMessage = ref<string>('')
  const connectionStatus = ref<string>('disconnected')
  const lastError = ref<string | null>(null)

  // 计算属性
  const currentSession = computed(() => {
    return currentSessionId.value ? sessions.value.get(currentSessionId.value) : null
  })

  const currentMessages = computed(() => {
    return currentSessionId.value ? messages.value.get(currentSessionId.value) || [] : []
  })

  const hasCurrentSession = computed(() => {
    return currentSessionId.value !== null
  })

  const canSendMessage = computed(() => {
    return hasCurrentSession.value && !isStreaming.value && connectionStatus.value === 'connected'
  })

  const sessionCount = computed(() => {
    return sessions.value.size
  })

  const allSessions = computed(() => {
    return Array.from(sessions.value.values()).sort((a, b) => 
      new Date(b.id).getTime() - new Date(a.id).getTime()
    )
  })

  // 私有方法
  const generateMessageId = (): string => {
    return `msg_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
  }

  const addMessage = (sessionId: string, message: Omit<ChatMessage, 'id' | 'timestamp'>): ChatMessage => {
    const newMessage: ChatMessage = {
      ...message,
      id: generateMessageId(),
      timestamp: new Date()
    }

    const sessionMessages = messages.value.get(sessionId) || []
    sessionMessages.push(newMessage)
    messages.value.set(sessionId, sessionMessages)

    return newMessage
  }

  // 会话管理
  const createSession = async (): Promise<string> => {
    try {
      const sessionId = `session_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
      
      const session: ChatSession = {
        id: sessionId,
        isStreaming: false,
        currentMessage: '',
        tasks: [],
        executionStatus: null,
        error: null
      }

      sessions.value.set(sessionId, session)
      messages.value.set(sessionId, [])
      
      return sessionId
    } catch (error) {
      lastError.value = error instanceof Error ? error.message : '创建会话失败'
      throw error
    }
  }

  const setCurrentSession = (sessionId: string | null) => {
    currentSessionId.value = sessionId
    
    // 重置流式状态
    isStreaming.value = false
    currentStreamingMessage.value = ''
    lastError.value = null
  }

  const deleteSession = (sessionId: string) => {
    sessions.value.delete(sessionId)
    messages.value.delete(sessionId)
    
    if (currentSessionId.value === sessionId) {
      currentSessionId.value = null
    }
    
    // 清理聊天服务中的会话
    chatService.clearSession(sessionId)
  }

  const clearAllSessions = () => {
    sessions.value.clear()
    messages.value.clear()
    currentSessionId.value = null
    isStreaming.value = false
    currentStreamingMessage.value = ''
    lastError.value = null
    
    chatService.clearAllSessions()
  }

  // 消息发送
  const sendMessage = async (
    content: string, 
    options?: ChatCompletionRequest['custom']
  ): Promise<void> => {
    if (!currentSessionId.value) {
      throw new Error('No active session')
    }

    try {
      // 添加用户消息
      addMessage(currentSessionId.value, {
        sessionId: currentSessionId.value,
        role: 'user',
        content,
        type: 'text'
      })

      // 开始流式处理
      isStreaming.value = true
      currentStreamingMessage.value = ''
      lastError.value = null

      // 准备消息历史
      const sessionMessages = messages.value.get(currentSessionId.value) || []
      const messageHistory = sessionMessages.map(msg => ({
        role: msg.role,
        content: msg.content
      }))

      // 发送到聊天服务
      await chatService.startChat(messageHistory, currentSessionId.value, options)

      // 监听流式响应
      startStreamingMonitor()

    } catch (error) {
      isStreaming.value = false
      lastError.value = error instanceof Error ? error.message : '发送消息失败'
      throw error
    }
  }

  const stopStreaming = () => {
    if (currentSessionId.value) {
      chatService.stopStreaming(currentSessionId.value)
      
      // 如果有部分消息，保存为助手消息
      if (currentStreamingMessage.value.trim()) {
        addMessage(currentSessionId.value, {
          sessionId: currentSessionId.value,
          role: 'assistant',
          content: currentStreamingMessage.value,
          type: 'text'
        })
      }
      
      isStreaming.value = false
      currentStreamingMessage.value = ''
    }
  }

  // 流式监听
  const startStreamingMonitor = () => {
    const monitorInterval = setInterval(() => {
      if (!currentSessionId.value) {
        clearInterval(monitorInterval)
        return
      }

      const session = chatService.getSession(currentSessionId.value)
      if (!session) {
        clearInterval(monitorInterval)
        return
      }

      // 更新会话状态
      sessions.value.set(currentSessionId.value, session)
      
      // 更新流式消息
      if (session.isStreaming) {
        currentStreamingMessage.value = session.currentMessage
      } else {
        // 流式结束，保存最终消息
        if (session.currentMessage.trim()) {
          addMessage(currentSessionId.value, {
            sessionId: currentSessionId.value,
            role: 'assistant',
            content: session.currentMessage,
            type: 'text'
          })
        }
        
        isStreaming.value = false
        currentStreamingMessage.value = ''
        clearInterval(monitorInterval)
      }

      // 更新错误状态
      if (session.error) {
        lastError.value = session.error
        isStreaming.value = false
        clearInterval(monitorInterval)
      }

    }, 100) // 每100ms检查一次
  }

  // 任务操作
  const confirmTaskExecution = async (): Promise<void> => {
    if (!currentSessionId.value) {
      throw new Error('No active session')
    }

    try {
      await chatService.confirmTaskExecution(currentSessionId.value)
      
      // 添加系统消息
      addMessage(currentSessionId.value, {
        sessionId: currentSessionId.value,
        role: 'system',
        content: '任务执行已确认，开始处理...',
        type: 'system'
      })

    } catch (error) {
      lastError.value = error instanceof Error ? error.message : '确认执行失败'
      throw error
    }
  }

  const modifyTasks = async (modification: any): Promise<void> => {
    if (!currentSessionId.value) {
      throw new Error('No active session')
    }

    try {
      await chatService.modifyTasks(currentSessionId.value, modification)
      
      // 添加系统消息
      addMessage(currentSessionId.value, {
        sessionId: currentSessionId.value,
        role: 'system',
        content: '任务已修改',
        type: 'system'
      })

    } catch (error) {
      lastError.value = error instanceof Error ? error.message : '修改任务失败'
      throw error
    }
  }

  const cancelExecution = async (): Promise<void> => {
    if (!currentSessionId.value) {
      throw new Error('No active session')
    }

    try {
      await chatService.cancelExecution(currentSessionId.value)
      
      // 添加系统消息
      addMessage(currentSessionId.value, {
        sessionId: currentSessionId.value,
        role: 'system',
        content: '任务执行已取消',
        type: 'system'
      })

    } catch (error) {
      lastError.value = error instanceof Error ? error.message : '取消执行失败'
      throw error
    }
  }

  // 消息操作
  const editMessage = (messageId: string, newContent: string): boolean => {
    if (!currentSessionId.value) return false

    const sessionMessages = messages.value.get(currentSessionId.value)
    if (!sessionMessages) return false

    const message = sessionMessages.find(m => m.id === messageId)
    if (message && message.role === 'user') {
      message.content = newContent
      return true
    }

    return false
  }

  const deleteMessage = (messageId: string): boolean => {
    if (!currentSessionId.value) return false

    const sessionMessages = messages.value.get(currentSessionId.value)
    if (!sessionMessages) return false

    const messageIndex = sessionMessages.findIndex(m => m.id === messageId)
    if (messageIndex > -1) {
      sessionMessages.splice(messageIndex, 1)
      return true
    }

    return false
  }

  const clearMessages = (sessionId?: string): void => {
    const targetSessionId = sessionId || currentSessionId.value
    if (targetSessionId) {
      messages.value.set(targetSessionId, [])
    }
  }

  // 连接状态监听
  const updateConnectionStatus = (status: string) => {
    connectionStatus.value = status
  }

  // 工具方法
  const exportSession = (sessionId?: string) => {
    const targetSessionId = sessionId || currentSessionId.value
    if (!targetSessionId) return null

    const session = sessions.value.get(targetSessionId)
    const sessionMessages = messages.value.get(targetSessionId)

    return {
      sessionId: targetSessionId,
      session,
      messages: sessionMessages,
      exportedAt: new Date().toISOString(),
      version: '1.0'
    }
  }

  const getMessageCount = (sessionId?: string): number => {
    const targetSessionId = sessionId || currentSessionId.value
    if (!targetSessionId) return 0

    const sessionMessages = messages.value.get(targetSessionId)
    return sessionMessages ? sessionMessages.length : 0
  }

  const getLastMessage = (sessionId?: string): ChatMessage | null => {
    const targetSessionId = sessionId || currentSessionId.value
    if (!targetSessionId) return null

    const sessionMessages = messages.value.get(targetSessionId)
    return sessionMessages && sessionMessages.length > 0 
      ? sessionMessages[sessionMessages.length - 1] 
      : null
  }

  // 重置方法
  const resetChat = () => {
    sessions.value.clear()
    messages.value.clear()
    currentSessionId.value = null
    isStreaming.value = false
    currentStreamingMessage.value = ''
    connectionStatus.value = 'disconnected'
    lastError.value = null
  }

  return {
    // 状态
    sessions: readonly(sessions),
    messages: readonly(messages),
    currentSessionId: readonly(currentSessionId),
    isStreaming: readonly(isStreaming),
    currentStreamingMessage: readonly(currentStreamingMessage),
    connectionStatus: readonly(connectionStatus),
    lastError: readonly(lastError),

    // 计算属性
    currentSession,
    currentMessages,
    hasCurrentSession,
    canSendMessage,
    sessionCount,
    allSessions,

    // 会话管理
    createSession,
    setCurrentSession,
    deleteSession,
    clearAllSessions,

    // 消息发送
    sendMessage,
    stopStreaming,

    // 任务操作
    confirmTaskExecution,
    modifyTasks,
    cancelExecution,

    // 消息操作
    editMessage,
    deleteMessage,
    clearMessages,

    // 连接状态
    updateConnectionStatus,

    // 工具方法
    exportSession,
    getMessageCount,
    getLastMessage,

    // 重置
    resetChat
  }
})